package com.facebank.usersupport.controller;

import com.facebank.usersupport.common.MessageKeyEnum;
import com.facebank.usersupport.model.RestModel;
import com.facebank.usersupport.service.ITravelDetailService;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpiderController {

    @Autowired
    private ITravelDetailService travelDetailService;

    @RequestMapping("/spider/crawl")
    public RestModel crawl(@RequestParam("number") String number){
        if(StringUtils.isBlank(number)){
            return new RestModel(MessageKeyEnum.PARAM_EMPTY.getCode(),MessageKeyEnum.PARAM_EMPTY.getMessage());
        }
        if(NumberUtils.isNumber(number)){
            String url = "http://www.szcits.cn/line/"+number+".html";
            int key = travelDetailService.getDetail(url,Integer.parseInt(number));
            if(0==key){
                return new RestModel(MessageKeyEnum.ERROR.getCode(),MessageKeyEnum.ERROR.getMessage());
            }else {
                return new RestModel(MessageKeyEnum.SUCCESS.getCode(),MessageKeyEnum.SUCCESS.getMessage());
            }
        }
        String[] splits = number.split(",");
        if(splits.length>2||splits.length<1){
            return new RestModel(MessageKeyEnum.PARAM_ILLEGAL.getCode(),MessageKeyEnum.PARAM_ILLEGAL.getMessage());
        }
        if(NumberUtils.isNumber(splits[0])&&NumberUtils.isNumber(splits[1])){
            for (int i = Integer.parseInt(splits[0]);i<=Integer.parseInt(splits[1]);i++){
                String url = "http://www.szcits.cn/line/"+i+".html";
                travelDetailService.getDetail(url,i);
            }
            return new RestModel(MessageKeyEnum.SUCCESS.getCode(),MessageKeyEnum.SUCCESS.getMessage());
        }else {
            return new RestModel(MessageKeyEnum.PARAM_ILLEGAL.getCode(),MessageKeyEnum.PARAM_ILLEGAL.getMessage());
        }
    }
}
